package org.jeecg.modules.online.cgform.util;

import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

/**
 * Author: zh
 * Desc: 压缩包工具类
 * Date: Created in 2018/5/19 13:51
 */
public class GenerateCodeFileToZip {

    /**
     * 把文件集合打成zip压缩包
     *
     * @param srcFilePaths 压缩文件集合
     * @param zipFilePath  zip文件名
     * @throws RuntimeException 异常
     */
    public static File toZip(List<String> srcFilePaths, String zipFilePath) throws RuntimeException {
        File zipFile = FileUtil.touch(zipFilePath);
        if (zipFile == null) {
            return null;
        }
        if (!zipFile.getName().endsWith(".zip")) {
            return null;
        }
        ZipOutputStream zos = null;
        try {
            FileOutputStream out = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(out);
            for (String srcFilePath : srcFilePaths) {
                //TODO 此处逻辑不通用
                srcFilePath = URLDecoder.decode(srcFilePath, "UTF-8").replace("生成成功：", "");
                File srcFile = new File(srcFilePath);
                if (srcFile == null || !srcFile.exists()) {
                    continue;
                }
                byte[] buf = new byte[BUFFER_SIZE];
                String filePathName = null;
                //TODO 此处逻辑不通用
                if (srcFile.getAbsolutePath().indexOf("src\\") != -1) {
                    filePathName = srcFile.getAbsolutePath().substring(srcFile.getAbsolutePath().indexOf("src\\") - 1);
                } else {
                    filePathName = srcFile.getAbsolutePath().substring(srcFile.getAbsolutePath().indexOf("src/") - 1);
                }
                //System.out.println(filePathName);
                zos.putNextEntry(new ZipEntry(filePathName));
                //System.out.println("srcFile.getName()" + srcFile.getName());
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    System.out.println("ZipUtil toZip close exception" + e);
                }
            }
            out.close();
        } catch (Exception e) {
            throw new RuntimeException("zipFile error from ZipUtils", e);
        }
        return zipFile;
    }

}
